package com.seecoder.BlueWhale.util;

import com.seecoder.BlueWhale.exception.BlueWhaleException;
import com.seecoder.BlueWhale.po.User;
import org.openxmlformats.schemas.drawingml.x2006.chart.STBarDir;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @Author: DingXiaoyu
 * @Date: 0:28 2023/11/26
 * 你可以通过这个类的方法来获得当前用户的信息。
 */
@Component
public class SecurityUtil {

    @Autowired
    HttpServletRequest httpServletRequest;

    public User getCurrentUser() {
        return (User) httpServletRequest.getSession().getAttribute("currentUser");
    }

    public int getUserId() {
        return getCurrentUser().getId();
    }


    public static String encryptSha256(String value) {
        MessageDigest digest;
        String ans;
        try {
            digest = MessageDigest.getInstance("SHA-256");
            byte[] encodedHash = digest.digest(value.getBytes(StandardCharsets.UTF_8));
            ans = byte2Hex(encodedHash);
        } catch (Exception e) {
            System.err.println();
            throw BlueWhaleException.sha256Error();
        }
        return ans;
    }

    private static String byte2Hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xff);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
